<template>
  <div class="filterBox" v-isSelf="handleClose">
    <el-popover
      class="filterBox"
      ref="filterBox"
      :visible="state.show"
      trigger="click"
      placement="bottom"
      popper-class="popperClass"
      :width="width"
    >
      <template #reference>
        <div
          class="aic"
          :style="align == 'left' ? {} : { justifyContent: 'center' }"
        >
          {{ title }}
          <div v-if="isFilter" class="fdc aic pl-5" @click.stop="handleOrder()">
            <span
              :class="[
                isTop ? 'colorActive' : '',
                'el-icon-caret-top displayBlock',
              ]"
              style="line-height: 0.4rem; color: #9999"
            ></span>
            <span
              :class="[
                isBottom ? 'colorActive' : '',
                'el-icon-caret-bottom displayBlock',
              ]"
              style="line-height: 0.4rem; color: #9999"
            ></span>
          </div>
          <el-icon
            v-if="!isFilter"
            @click.stop="handleShow"
            style="font-size: 14px; color: #9999"
            :class="[
              state.values.length > 0 || state.value ? 'colorActive' : '',
            ]"
            ><iconLouDou
          /></el-icon>
        </div>
      </template>
      <div>
        <div v-if="flterType == 'select'">
          <el-input
            placeholder="请输入内容"
            v-model="filterKey"
            size="mini"
            @change="handleFilter"
            @blur="show = false"
            clearable
          >
          </el-input>

          <el-checkbox-group
            v-model="state.values"
            class="overflowY mt10"
            style="height: 100px"
          >
            <el-checkbox
              class=""
              v-for="(item, index) in options"
              :key="index"
              :label="item"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
          <div
            style="
              border-top: 1px solid #dddfe6;
              text-align: center;
              padding-top: 15px;
            "
          >
            <el-button size="mini" @click="handleSearch" type="primary"
              >确定</el-button
            >
            <el-button size="mini" @click="cancelBtn">取消</el-button>
          </div>
        </div>
        <div v-if="flterType == 'input'">
          <el-input
            placeholder="请输入内容 后回车"
            v-model="state.value"
            ref="inputKey"
            size="mini"
            @change="handleInputData"
            clearable
          >
          </el-input>
        </div>
        <div v-if="flterType == 'number'">
          <el-input
            placeholder="请输入内容 后回车"
            v-model="state.value"
            ref="inputKey"
            size="mini"
            type="number"
            @change="handleInputData"
            clearable
          >
          </el-input>
        </div>
        <div v-if="flterType == 'datetimerange'">
          <el-date-picker
            v-model="state.values"
            type="datetimerange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            @change="handleFilterDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'daterange'">
          <el-date-picker
            v-model="state.values"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            @change="handleFilterDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'years'">
          <el-date-picker
            v-model="state.values"
            value-format="yyyy"
            type="years"
            @change="handleFilterYears"
          >
          </el-date-picker>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  defineEmits,
  onMounted,
  nextTick,
  computed,
  watch,
} from "vue";
const emit = defineEmits(["change"]);
import filterTag from "/@/components/Filter/filterTag.vue";
import { getDicts } from "/@ts/axios/urlApi/system";
import { store } from "/@ts/store/index";
/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/
// const store  = useStops()
const state: any = reactive({
  filterKey: "",
  isTop: false,
  isBottom: false,
  show: false,
  options: [],
  optionsCopy: [],
  values: [],
  years: "",
  value: "",
  deptOptions: [],
  allDeptList: [],
  visible: false,
});
const handleShow = () => {
  state.show = !state.show;
  nextTick(() => {
    document.querySelectorAll(".popperClass").forEach((ele: any) => {
      ele.addEventListener("click", (e: any) => {
        e.stopPropagation();
      });
    });
  });
};
const props: any = defineProps({
  valueKey: {
    //api 对应的函数 名字
    type: String,
    default: "",
  },
  params: {
    //api 传递 的 参数
    type: Object,
    default: () => {},
  },
  title: {
    //标题名字
    type: String,
    default: "",
  },
  isFilter: {
    // 是否有 排序
    type: Boolean,
    default: false,
  },
  orderDef: {
    type: String,
    default: "",
  },
  dictType: {
    //筛选类型  ==""&&isFilter==true 为 排序模式
    type: String,
    default: "",
  },
  flterType: {
    //筛选类型  ==""&&isFilter==true 为 排序模式
    type: String,
    default: "select",
  },
  width: {
    //筛选类型
    type: [Number, String],
    default: 200,
  },
  data: {
    //数据同步 字段
    type: [Number, String, Array, Object],
    default: () => {},
  },
  list: {
    //筛选数据
    type: Array,
    default: () => [],
  },
  align: {
    type: String,
    default: "left",
  },
});

watch(
  () => props.data,
  (val) => {
    if (val) {
      const values = val[props.valueKey];
      console.log("values :>> ", values);
      if (!values) {
        state.values = [];
        state.value = "";
        state.show = false;
        return;
      }

      const dataType = ["years", "select", "datetimerange", "daterange"];
      if (dataType.includes(props.flterType)) {
        state.values = values.map((res: any) => res.value);
      }
      const dataType3 = ["input", "number"];
      if (dataType3.includes(props.flterType)) {
        if (values.length == 0) {
          state.value = "";
          state.show = false;
        }
      }
    }
  },
  {
    deep: true,
  },
);

const handleFilter = () => {
  if (state.filterKey == "") {
    state.options = state.optionsCopy;
    return;
  }
  state.options = state.optionsCopy.filter((res: any) => {
    if (res.label.indexOf(state.filterKey) != -1) return res;
  });
};
const handleSearch = () => {
  state.show = false;

  emit("change", {
    data: state.values,
    valueKey: props.valueKey,
    title: props.title,
    type: "multi",
  });
};
const cancelBtn = () => {
  state.show = false;
  state.values = [];
  state.value = null;
  emit("change", {
    data: [],
    valueKey: props.valueKey,
    title: props.title,
    type: "single",
  });
};
const getData = (key: any) => {
  getDicts(key).then((response: any) => {
    state.options = response.data.map((item: any) => {
      return {
        label: item.dictLabel,
        value: item.dictValue,
        raw: item,
      };
    });
    state.optionsCopy = JSON.parse(JSON.stringify(state.options));
  });
};
const handleClose = (val: any) => {
  if (props.flterType != "user") {
    state.show = false;
  }
};
const handleFilterDate = (val: any) => {
  state.show = false;
  emit("change", {
    data: [
      {
        value: val,
        label: `${val[0]}~${val[1]}`,
      },
    ],
    valueKey: props.valueKey,
    title: props.title,
    type: "single",
  });
};
const handleFilterYears = (val: any) => {
  state.show = false;
  if (val) {
    emit("change", {
      data: val.map((res: any) => {
        return {
          value: res,
          label: res,
        };
      }),
      valueKey: props.valueKey,
      title: props.title,
      type: "multi",
    });
  } else {
    emit("change", {
      data: [],
      valueKey: props.valueKey,
      title: props.title,
      type: "multi",
    });
  }
};
const handleInputData = (val: any) => {
  state.show = false;
  let data: any = [];
  if (val) {
    data = [
      {
        value: val,
        label: val,
      },
    ];
  }
  emit("change", {
    data: data,
    valueKey: props.valueKey,
    title: props.title,
    type: "single",
  });
};
const themecolor = computed(() => {
  const themecolor: any = store.state.themeColor;
  console.log("state :>> ", state);
  return `rgba(${themecolor[0]},${themecolor[1]},${themecolor[2]}, 1)`;
});
</script>

<style lang="scss">
.colorActive {
  color: v-bind(themecolor) !important;
}
.filterBtn:hover {
  color: v-bind(themecolor) !important;
}

.filterBox.el-popover.popperClass {
  min-width: 80px;
  z-index: 1000 !important;
}
</style>
